<?php
namespace app\api\model\food;
use app\common\model\User as UserModel;
use hema\wechat\Driver as Wechat;
use hema\wechat\WxBizDataCrypt;
use app\api\model\Setting as SettingModel;
use hema\wechat\Pay as WxPay;
use think\facade\Cache;
/**
 * 用户模型类
 */
class User extends UserModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [];
    /**
     * 显示等级
     */
    public function getVAttr($value,$data)
    {
        $grade = Setting::getItem('vip');
        if($value > 0 or $grade['open_mode'] == 'score'){
            //判断是否升级
            if($data['score'] >= $grade['vip'][$value]['score']){
                $value = $value + 1;//等级加1
                $user = self::get($data['user_id']);
                $user->v = $value;//升级
                $user->save();
                //升级任务
                if(isset($grade['vip'][$value-1]['gift']) AND sizeof($grade['vip'][$value-1]['gift']) > 0){
                    $coupon = new CouponUser;
                    $coupon->add($grade['vip'][$value-1]['gift'],$data['user_id']);
                }
            }
            $grade['lving'] = 100;//据升下一级完成百分比
            $grade['lack'] = 0;//升下一级所需积分
            //如果已经是最高级别
            if($value == 6){
               $grade['upper'] = $grade['vip'][$value-1]['score']; 
            }else{
                $grade['upper'] = $grade['vip'][$value]['score'];//下一级所需积分总额
                $m = $grade['upper'] - $grade['vip'][$value-1]['score']; //上下另个级别相差积分
                $x = $data['score'] - $grade['vip'][$value-1]['score'];//计算出超过当前等级的积分
                $grade['lack'] = $m - $x;//计算升到下一级还需要多少积分
                $grade['lving'] = round($x/$m*100); //计算已经完成百分比
                
            }
            return ['value' => $value,'text' => $grade['vip'][$value-1]['name'],'grade' => $grade];
        }else{
            return ['value' => $value,'text' => '普通用户','grade' => $grade];
        }
    }
    /**
     * 获取用户信息
     */
    public static function getDetail($user_id)
    {
	    if($user = self::get($user_id)){
            return $user;
        } 
        return false;
    }
    /**
     * 微信小程序用户登录
     */
    public function login(array $data)
    {
        $userInfo = json_decode(htmlspecialchars_decode($data['user_info']), true);
        //微信登录 (获取session_key)
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($data['code'],$data['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        if ($user = $this->where(['open_id' => $result['openid']])->find()) {
            $userInfo['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $userInfo['nickName']);
            $userInfo['avatar'] = $userInfo['avatarUrl'];
            if (!$user->save($userInfo)) {
                $this->error = '用户信息更新失败';
                return false;
            }
            return $user;
        }
        $this->error = '用户不存在';
        return false;
    }
    
    /**
     * 微信小程序用户自动注册/登录
     */
    public function autoLogin(array $data)
    {
        //微信登录 (获取session_key)
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($data['code'],$data['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        if(isset($result['unionid'])){
            $userInfo['union_id'] = $result['unionid'];
        }
        if (!$user = $this->where(['open_id' => $result['openid']])->find()) {
            //用户不存在才执行
            $userInfo['open_id'] = $result['openid'];
            $userInfo['applet_id'] = $data['applet_id'];
            $userInfo['status'] = 10;
            $this->save($userInfo);
            $user = $this->where(['open_id' => $result['openid']])->find();
        }
        return $user;
    }
    /**
     * 获取用户手机号
     */
    public function getPhoneNumber($post, $userInfo)
    {
        // 微信登录 获取session_key
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($post['code'],$post['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        $sessionKey = $result['session_key'];
        $encryptedData= $post['encryptedData'];
        $iv = $post['iv'];
        $pc = new WxBizDataCrypt($sessionKey,$post['applet_id']);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);
        $data = json_decode($data,true);
        if (isset($data['phoneNumber'])) {
            $userInfo->phone = $data['phoneNumber'];
            $userInfo->save();
            return true;
        }
        return false;
    }
    /**
     * 公众号授权登陆
     */
    public function auth($code,$appid)
    {
        $wx = new Wechat;
        if (!$result = $wx->oauth2($code,$appid,self::$applet_id)) {
            $this->error = $wx->getError();
            return false;
        }
        if (!$user = $this->where(['open_id' => $result['openid']])->find()) {
            //用户不存在才执行
            if (!$result = $wx->getUserinfo($result['openid'],$result['access_token'])) {
                $this->error = $wx->getError();
                return false;
            }
            $data = [
                'open_id' => $result['openid'],
                'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $result['nickname']),
                'avatar' => $result['headimgurl'],
                'gender' => $result['sex'],
                'country' => $result['country'],
                'province' => $result['province'],
                'city' => $result['city'],
                'platform' => 20,
                'status' => 10,
                'applet_id' => self::$applet_id,
            ];
            if(isset($result['unionid'])){
                $data['union_id'] = $result['unionid'];
            }
            $this->save($data);
            $user = $this->where(['open_id' => $result['openid']])->find();
        }
        return $user;
    }
    
    /**
     * 获取开通会员支付详情 - 微信回调
     */
    public function payDetail(string $order_no)
    {
        return Cache::get($order_no);
    }

    /**
     * 更新用户会员状态 - 微信回调
     */
    public function updatePayStatus(string $transaction_id, array $data)
    {
        //更新用户会员状态
		$user = self::get($data['user_id']);
		$user->v = 1;//开通会员
		$user->score = ['inc', (int)$data['money']];//增加积分
		$user->pay = ['inc', $data['money']];//增加消费金额
		$user->save();
		//增加消费记录
		$model = new Record;
		$data['action'] = 40;//消费
		$data['type'] = 30;//微信
        $model->save($data);
        //账单分账
        $wxpay = new WxPay(SettingModel::getItem('wxpay',$data['applet_id']));
        $wxpay->divide([
            'out_order_no' => $data['order_no'],
            'transaction_id' => $transaction_id,
            'total' => $data['money'],
        ],$data['applet_id']);//进行分账
		return true;
    }
}